//
//  WBNetWorkManager+Extension.swift
//  simpleWeibo
//
//  Created by 孙林 on 2018/1/20.
//  Copyright © 2018年 孙林. All rights reserved.
//

import Foundation

// MARK: - 封装微博的网络请求方法
extension WBNetWorkManager {
    
    /// 加载微博数据字典数组
    ///
    /// - Parameters:
    ///   - since_id: 返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 返回ID小于或等于max_id的微博，默认为0。
    ///   - completion: 完成回调 list:[微博字典数组] 和 是否成功
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion:@escaping (_ list:[[String: AnyObject]]?, _ isSuccess: Bool)->()) {
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        //Swift中: Int64可以转成AnyObject, 但Int64不行
        let parameters = ["since_id": "\(since_id)",
            "max_id": "\(max_id > 0 ? max_id - 1 : 0)"
                            ]
        
        tokenRequest(method: .GET, URLString: url, parameters: parameters as [String : AnyObject]) { (json, isSuccess) in
            let result = json?["statuses"] as? [[String: AnyObject]]
            completion(result, isSuccess)
            
        }
        
    }
    
    func unreadCount(completion: @escaping (_ count: Int)->()) {
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid": uid]
        tokenRequest(method: .GET, URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            let dict = json as? [String: AnyObject]
            let count = dict?["status"] as? Int
            completion(count ?? 0)
        }
    }
}

extension WBNetWorkManager {
    
    
    /// 发布微博接口
    ///
    /// - Parameters:
    ///   - text: text 发布的微博正文
    ///   - image: image 配图
    ///   - completion: completion 完成回调
    func postStatus(text: String, image: UIImage?, completion: @escaping (_ result: [String :AnyObject]?, _ isSuccess: Bool) -> ()) -> () {
        
        var urlString: String
        //1 url
        if image != nil {
            urlString = "https://api.weibo.com/2/statuses/update.json"
        } else {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        }
        
        //2 参数字典
        let parames = ["status": text]
        
        //3 如果图像不为空 需要设置 name 和 data
        var name: String?
        var data: Data?
        if image != nil {
            name = "pic"
            data = image!.pngData()
        } else {
            name = nil
            data = nil
        }
        
        //4 发起网络请求
        tokenRequest(method: .POST, URLString: urlString, parameters: parames as [String : AnyObject], name: name, data: data) { (json, isSuccess) in
            completion(json as? [String : AnyObject], isSuccess)
        }
    }
}
//"https://api.weibo.com/2/statuses/update.json"

extension WBNetWorkManager {
    ///获取用户个人信息
    func loadUserInfo(completion: @escaping (_ dict: [String : AnyObject]) -> ()) {
        guard let uid = userAccount.uid else {
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid" : uid]
        tokenRequest(method: .GET, URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            //完成回调
            completion(json as? [String: AnyObject] ?? [:])
        }
    }
};

// MARK: - OAuth相关方法
extension WBNetWorkManager {
    /// 加载AccessToken
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool)->() ) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id":WBAppKey,
                      "client_secret":WBAppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":WBRedirectURI
                      ]
        
        request(method: .POST, URLString: urlString, parameters: params as [String : AnyObject] ) { (json, isSuccess) in
            self.userAccount.yy_modelSet(with: (json as? [String : AnyObject]) ?? [:])
            print(self.userAccount)
            self.loadUserInfo(completion: { (json) in
                print("\(json)")
                self.userAccount.yy_modelSet(with: json)
                self.userAccount.saveAccount()
                completion(isSuccess)
            })
        }
    }
}
